package com.vegetable.modules.service.bank.convert;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.vegetable.modules.entity.bank.vo.RCBCTran;
import com.vegetable.modules.entity.finance.Transactions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 农信流水标准化字段输出
 */
@Slf4j
public class RCBConverter extends BankGenerator {
	private static final String bankMark = "PSBC";

	public List<Transactions> convert(MultipartFile file) throws Exception {
		List<Transactions> targetJson = new ArrayList<>();
		try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
			Sheet sheet = workbook.getSheetAt(0);
			Row headRow = sheet.getRow(5);
			Short cellNum = headRow.getLastCellNum();
			Field[] fields = RCBCTran.class.getDeclaredFields();
			List<Field> cFields = Arrays.stream(fields).filter(el -> el.getAnnotation(Excel.class) != null).collect(Collectors.toList());
			for(int i = 0; i < cellNum; i ++){
				String cellName = headRow.getCell(i).getStringCellValue();
				String fieldName = cFields.get(i).getAnnotation(Excel.class).name();
				if(StrUtil.equals(cellName, fieldName)){
					log.info("格式是对的.");
				}else{
					throw new RuntimeException("格式不对了！！！");
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}

		ImportParams importParams = new ImportParams();
		importParams.setNeedVerify(true);
		importParams.setHeadRows(5);
		List<RCBCTran> orderList = ExcelImportUtil.importExcel(file.getInputStream(), RCBCTran.class, importParams);

		if(CollectionUtil.isNotEmpty(orderList)){
			for(RCBCTran payTran : orderList){
				Transactions tmp = new Transactions();
				BeanUtils.copyProperties(payTran, tmp);
				tmp.setTradingType(payTran.getTradingType().equals("汇出") ? "EXPENSE" : "INCOME");
				tmp.setTradingAmount(payTran.getTradingAmount());
				tmp.setStatus("SUCCESS");
				tmp.setTradingDescription(payTran.getSummary());
				tmp.setTradingTime(payTran.getTranDate());
				tmp.setChannel(bankMark);
				tmp.setTradingNo(Transactions.generateUniqueFlowId(tmp));
				targetJson.add(tmp);
			}
		}
		return targetJson;
	}
}
